//话题详情
var lotteryNew = (function () {
    return {
        lottery_id: "",//若当前是修改话题信息，则保持话题ID
        status: -1,
        _bootbox: {},//遮罩弹窗的句柄
        startTime: "",//起始时间

        //初始化函数
        init: function () {
            var self = this;

            momo.initPage();
            momo.addPageEvent(self);
            $(".routing").attr("data-route", "lottery.html");

            // icely add（输入限制）
            momo.inputText('.name', 20);
            momo.inputText('.lotteryName', 20);
            momo.inputText('.lotteryNum', 8);
            $('.lotteryNum').attr('min', '0').attr( 'max', '99999999').css('width', '90%');
            // 监听显示 得到焦点时，可能修改内容，全选内容
            $('.lotteryName').focus(function( event ){
                event.target.select();
            });

            // 监听库存 失去焦点时，值是否为非负整数（负数？小数？）
            $('.lotteryNum').change( function(){
                if( parseInt( $(this).val() ) < 0  ||  parseInt( $(this).val() ) != $(this).val() ){
                    alert('库存只能输入0和正整数！');
                    $(this).focus().select();
                }
            });

            $('.lotteryRand').change( function(){
                if( parseInt( $(this).val() ) > 10000 || parseInt( $(this).val() ) < 0  ||  parseInt( $(this).val() ) != $(this).val() ){
                    alert('概率只能输入0～10000的整数！');
                    $(this).focus().select();
                }
            });

            $(document).on("click", ".addBtn", this.newItem.bind(this));


            //点击发布
            $(document).on("click", ".submitBtn", this.addItem.bind(this));

            //取消新建
            $(document).on("click", ".cancelBtn2", function () {location.href = "./lottery.html";});

            //是否修改内容
            if (momo.getURLElement("id")) {
                self.lottery_id = momo.getURLElement("id");
                self.setData();
                $(".path").text("修改抽奖活动");

            }
            else{
                self.initData();
                $(".path").text("增加抽奖活动");

            }

            $(".lotteryNum").attr("type", "text");
            $(".daterangepicker_start_input .input-mini").attr("readOnly", "true");

        },

        //添加话题//更新话题
        addItem: function () {
            var name = $(".name").val();
            var time = $(".time").val();
            var score = $(".score").val();
            var id = this.lottery_id;
            var timeArr = time.split(' - ');
            if(timeArr.length <= 1){
                alert("请输入有效期！");
                return;
            }
            var startTime = timeArr[0];
            var endTime = timeArr[1];

            var pirzeList = [];//奖品对象数组
            if (score <= 0) {
                alert("请输入抽奖消耗积分");
                return;
            }
            var pics=$(".uploadBtn");
            var lotteryNameDom = $(".lotteryName");
            var lotteryNumDom = $(".lotteryNum");
            var lotteryRandDom = $(".lotteryRand");

            var total=0;
            //遍历价格设置
            for (var i = 0; i < lotteryNameDom.length; i++) {
                var nameItem = lotteryNameDom.eq(i).val();
                var numItem = lotteryNumDom.eq(i).val();
                var idItem = lotteryNameDom.eq(i).data('id');
                var randItem = lotteryRandDom.eq(i).val();
                var url=pics.eq(i).attr('url');


                if (nameItem == "") {
                    alert("请输入奖品内容");
                    lotteryNameDom.eq(i).focus().select();
                    return;
                }
                if (numItem == "") {
                    alert("请输入奖品库存");
                    lotteryNumDom.eq(i).focus().select();
                    return;
                }
                if( parseInt( numItem ) < 0  ||  parseInt( numItem ) != numItem ){
                    alert('库存只能输入0和正整数！');
                    lotteryNumDom.eq(i).focus().select();
                    return;
                }
                if( parseInt(randItem) < 0 || parseInt(randItem) > 10000 || parseInt(randItem) != randItem){
                    alert('奖品概率设置错误');
                    lotteryRandDom.eq(i).focus().select();
                    return;
                }
                if(url==null || url.length<1){
                    alert('第'+(parseInt(i)+1)+'张图片还没上传');
                    return;
                }

                total+=parseInt(randItem);

                pirzeList.push({name: nameItem, sku: numItem, rand:randItem, id:idItem,url:url});
            }

            if(total!=10000){
                alert('奖品总概率必须等于10000，现在总值为'+total);
                return;
            }

            if (name == ""){
                alert("请输入活动名称！");
                return;
            }
            if (time == ""){
                alert("请输入有效期！");
                return;
            }
            if (score <= 0){
                alert('积分只能输入0和正整数！');
                return;
            }
            var body = {
                "id":id,
                "name": name,
                "start_time": startTime,
                "end_time": endTime,
                "score": score,
                "prizes": pirzeList
            };
            var url = (momo.getURLElement("id")?"PLottery/update":"PLottery/add");
            momo.sendPost(body, url, function (data) {
                if (data.errcode == 0) {
                    alert('操作成功');
                    window.location.href = "./lottery.html";
                }
                else alert(data.errmsg);
            }.bind(this));
        },

        newItem:function(){
            var html='';

            var i=$(".lotteryName").length;

            html+='<tr id="table_tr'+i+'"><th class="center">'+i+1+'</th>';
            html+='<th class="center "><div class="uploadDiv"><input class="uploadBtn"  target="'+i+'" id="uploadBtnFile'+i+'" type="file" url=""><img class="uploadBtn'+i+'" style="width:100%;height:100%" id="upImg'+i+'" src="/pufa/Themes/Admin/Public/img/addPictureBtn.png"></div></th>';
            html+='<th class="center"><input type="hidden" class="prizeId" value=""><input type="text" class="lotteryName" data-id=""  value="" /></th>';
            html+='<th class="center"><input type="number" class="lotteryRand" value=""/></th>';
            html+='<th class="center"><input type="number" class="lotteryNum" value=""/></th>';
            html+='<th class="center valueSum"></th>';

            html+='<th class="center valueSum"><a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="lotteryNew.delete(0,'+i+')">删除</a></th>';

            html+='</tr>';


            $('#lotteryBox').append($(html));

            $('.uploadBtn').unbind('change')
            $('.uploadBtn').change(function(e){
                lotteryNew.uploadChange(e);
            });

        },

        //获取并设置信息
        setData: function () {
            momo.sendPost({"id": this.lottery_id}, "PLottery/edit", function (data) {
                var type = momo.getURLElement("type");
                if (data.errcode == 0) {
                    data = data.data;

                    $(".name").val(data.name);
                    $(".score").val(data.score);
                    $(".time").val(data.start_time + " - " + data.end_time);


                    //修改时间选择控件
                    var picket = $("#datePicker").data('daterangepicker');
                    picket.language = "cn";
                    picket.setStartDate(data.start_time);
                    picket.setEndDate(data.end_time);


                    var html='';

                    for (var i = 0, length = data.prize.length; i < length; i++) {

                        var dataItem = data.prize[i];
                        html+='<tr id="table_tr'+i+'"><th class="center">'+i+1+'</th>';
                        html+='<th class="center "><div class="uploadDiv"><input class="uploadBtn"  target="'+i+'" id="uploadBtnFile'+i+'" type="file" url="'+dataItem.url+'"><img class="uploadBtn'+i+'" style="width:100%;height:100%" id="upImg'+i+'" src="'+(dataItem.url!='' ?dataItem.url:"/pufa/Themes/Admin/Public/img/addPictureBtn.png")+'"></div></th>';
                        html+='<th class="center"><input type="hidden" class="prizeId" value="'+dataItem.id+'"><input type="text" class="lotteryName" data-id="'+dataItem.id+'" '+(i==0?'readonly="readonly"':'')+' value="'+dataItem.name+'" /></th>';
                        html+='<th class="center"><input type="number" class="lotteryRand" value="'+dataItem.rand+'"/></th>';
                        html+='<th class="center"><input type="number" class="lotteryNum" value="'+dataItem.sku+'"/></th>';
                        html+='<th class="center valueSum">'+dataItem.surplus+'</th>';
                        if(i>0)
                            html+='<th class="center valueSum"><a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="lotteryNew.delete('+dataItem.id+','+i+')">删除</a></th>';
                        else
                            html+='<th class="center valueSum"></th>'
                        html+='</tr>';

                    }

                    $('#lotteryBox').html(html);

                    $('.uploadBtn').unbind('change')
                    $('.uploadBtn').change(function(e){
                        lotteryNew.uploadChange(e);
                    });

                }
                else console.log(data.errmsg);
            }.bind(this));
        },

        initData:function(){
            var html='';
            var i=0;

            html+='<tr id="table_tr'+i+'"><th class="center">'+i+1+'</th>';
            html+='<th class="center "><div class="uploadDiv"><input class="uploadBtn"  target="'+i+'" id="uploadBtnFile'+i+'" type="file" url=""><img class="uploadBtn'+i+'" style="width:100%;height:100%" id="upImg'+i+'" src="/pufa/Themes/Admin/Public/img/addPictureBtn.png"></div></th>';
            html+='<th class="center"><input type="hidden" class="prizeId" value=""><input type="text" class="lotteryName" data-id="" readonly="readonly" value="谢谢参与" /></th>';
            html+='<th class="center"><input type="number" class="lotteryRand" value=""/></th>';
            html+='<th class="center"><input type="number" class="lotteryNum" value=""/></th>';
            html+='<th class="center valueSum"></th>';

            html+='<th class="center valueSum"><a class="updateItem btn btn-mini btn-primary tableInnerBtn" onclick="lotteryNew.delete(0,'+i+')">删除</a></th>';

            html+='</tr>';

            $('#lotteryBox').html(html);

            $('.uploadBtn').unbind('change')
            $('.uploadBtn').change(function(e){
                lotteryNew.uploadChange(e);
            });
        },
        delete:function(id,index){
            if($(".lotteryName").length<4){
                alert('拥有的奖项不能小于3个');
                return;
            }
            if(confirm('确定删除吗？')){
                if(id==0){
                    $('#table_tr'+index).remove();
                    alert('删除成功');
                    return;
                }
                var url = "PLottery/delprize";
                momo.sendPost({id:id}, url, function (data) {
                    if (data.errcode == 0) {
                        $('#table_tr'+index).remove();
                        alert('删除成功');
                    }
                    else {
                        alert(data.errmsg);
                    }
                }.bind(this));
            }

        },
        uploadChange:function(e){

                var i=$(e.target).attr('target');
                var file = e.target.files[0];//获取用户选中的文件，并获取第一张

                var reader = new FileReader();//获取文件读取器
                reader.onloadend = function () {//文件加载完成

                    var img = new Image();//新建img对象
                    img.onload = function () {//设置其onload事件
                        var w = img.width;
                        var h = img.height * (w / img.width);
                        var canvas = document.createElement('canvas');
                        canvas.width = w; // 设置 canvas 的宽度和高度
                        canvas.height = h;
                        canvas.getContext('2d').drawImage(img, 0, 0, w, h);// 把图片绘制到 canvas 中
                        var dataURL = canvas.toDataURL('image/png');//借助canvas临时保存文件，用于在页面中使用img显示
                        $('#upImg'+i).attr('src',dataURL);

                        var projectImg_upLoadImg = new upLoadImg(null);
                        projectImg_upLoadImg.upLoadOne({dataURL:dataURL,name:file.name},function(url){

                            if(url.length>0)
                                $(e.target).attr('url',url);
                            else
                                alert('第'+(parseInt(i)+1)+'张图片上传失败');
                        });
                    };

                    img.src = reader.result;//加载img对象


                };
                reader.onerror = function () { console.error('reader error'); };
                reader.readAsDataURL(file);//实际操作，文件读取器，以URL的方式读取图片文件，使用base-64进行编码
        },

    }
})
();

var init = lotteryNew.init.bind(lotteryNew);